#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <time.h>
#include <sys/select.h>
#include <sys/time.h>

#define N 64
#define UDP_PORT 8888
#define TCP_PORT 9999
#define SERVER_IP "127.0.0.1"

int main() {
    int sockfd, udpfd;
    struct sockaddr_in server_addr, udp_addr, client_addr;
    char buf[N] = {0};
    socklen_t addrlen = sizeof(client_addr);

    // 创建TCP客户端套接字
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0) {
        perror("Socket creation failed");
        return -1;
    }

    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(TCP_PORT);
    if (inet_pton(AF_INET, SERVER_IP, &server_addr.sin_addr) <= 0) {
        perror("Invalid address");
        close(sockfd);
        return -1;
    }

    if (connect(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
        perror("Connection to server failed");
        close(sockfd);
        return -1;
    }

    printf("Connected to server\n");

    // 创建UDP套接字
    udpfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (udpfd < 0) {
        perror("UDP socket creation failed");
        close(sockfd);
        return -1;
    }

    // 设置UDP地址
    udp_addr.sin_family = AF_INET;
    udp_addr.sin_port = htons(UDP_PORT);
    udp_addr.sin_addr.s_addr = INADDR_ANY;

    // 绑定UDP套接字
    if (bind(udpfd, (struct sockaddr *)&udp_addr, sizeof(udp_addr)) < 0) {
        perror("UDP bind failed");
        close(sockfd);
        close(udpfd);
        return -1;
    }

    int device_online = 0;

    while (1) {
        // 发送 "Hello, STM32!" 消息
        const char *hello_msg = "Hello, STM32!";
        if (send(sockfd, hello_msg, strlen(hello_msg), 0) < 0) {
            perror("Send failed");
            device_online = 0;
        } else {
            printf("Sent: %s\n", hello_msg);
        }

        // 等待响应
        fd_set readfds;
        struct timeval timeout;
        FD_ZERO(&readfds);
        FD_SET(sockfd, &readfds);

        timeout.tv_sec = 5;
        timeout.tv_usec = 0;

        int activity = select(sockfd + 1, &readfds, NULL, NULL, &timeout);

        if (activity > 0 && FD_ISSET(sockfd, &readfds)) {
            ssize_t len = recv(sockfd, buf, N, 0);
            if (len > 0) {
                buf[len] = '\0';
                printf("Received: %s\n", buf);

                if (strcmp(buf, "Yes") == 0) {
                    device_online = 1;
                }
            } else {
                device_online = 0;
            }
        } else {
            device_online = 0;
        }

        // 监听UDP广播
        ssize_t len = recvfrom(udpfd, buf, N, 0, (struct sockaddr *)&client_addr, &addrlen);
        if (len < 0) {
            perror("recvfrom failed");
            continue;
        }

        buf[len] = '\0';
        printf("Received UDP message: %s\n", buf);

        // 检查是否为搜索请求
        if (strcmp(buf, "SEARCH_DEVICE") == 0) {
            const char *response;
            if (device_online) {
                response = "DeviceName|Online|192.168.28.100";
            } else {
                response = "DeviceName|offline|192.168.28.100";
            }
            sendto(udpfd, response, strlen(response), 0, (struct sockaddr *)&client_addr, addrlen);
            printf("Sent response: %s\n", response);
        }

        sleep(5);
    }

    close(sockfd);
    close(udpfd);

    return 0;
}